package com.lsl.test;

import cn.hutool.core.io.IoUtil;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @author lishuailong
 * @create 2020-07-10 11:40
 */
public class TCPtest1 {
    public static void main(String[] args) {

    }
    /**
     * 客户端
     */
    @Test
    public void client(){
        Socket socket=null;
        OutputStream os=null;
        try {
            InetAddress inetAddress =InetAddress.getByName("192.168.30.114");
            socket = new Socket(inetAddress,8899);
            os = socket.getOutputStream();
            IoUtil.write(os,false,"-1".getBytes());
            System.out.println("发送成功！");

        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IoUtil.close(os);
            IoUtil.close(socket);
        }
    }

    /**
     * 服务端
     */
    @Test
    public void server() throws IOException {
        ServerSocket serverSocket=null;
        Socket accept=null;
        InputStream inputStream=null;
        try {
            serverSocket = new ServerSocket(8899);
            while (true){

                accept = serverSocket.accept();
                inputStream = accept.getInputStream();
                byte[] bytes = IoUtil.readBytes(inputStream);
                String s = new String(bytes);
                if ("-1".equalsIgnoreCase(s)){
                    break;
                }
                System.out.println(s);
            }


        } finally {
            IoUtil.close(inputStream);
            IoUtil.close(accept);
            IoUtil.close(serverSocket);
        }


    }
}
